package dao

import (
	"time"

	"github.com/go-xorm/xorm"

	"im/common"
	"im/errcode"
	"im/model"
	"im/service/orm"
)

type GroupsMessagesPosts interface {
	// 创建群聊帖子或者更新一下更新时间
	Touch(m model.GroupsMessagesPostsModifiable) error
	
	// 获取某个群聊的帖子
	List(groupId int64) ([]model.Posts, error)
}

func NewGroupsMessagesPosts() GroupsMessagesPosts {
	return groupsMessagesPosts{db: orm.GetDB()}
}

type groupsMessagesPosts struct {
	db *xorm.Engine
}

func (g groupsMessagesPosts) Touch(m model.GroupsMessagesPostsModifiable) error {
	var row model.GroupsMessagesPosts
	found, err := g.db.Where("group_id=?", m.GroupId).Where("post_id=?", m.PostId).Get(&row)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed,err)
	}
	if found {
		row.Updated = common.Time(time.Now())
		_, err = g.db.Where("group_id=?", m.GroupId).Where("post_id=?", m.PostId).Cols("updated").Update(row)
	} else {
		row.GroupsMessagesPostsModifiable = m
		_, err = g.db.InsertOne(&row)
	}
	if err != nil {
		return errcode.NewError(errcode.DaoFailed,err)
	}
	return nil
}
func (g groupsMessagesPosts) List(groupId int64) ([]model.Posts, error) {
	var ms []model.Posts
	err := g.db.Where("group_id=?", groupId).OrderBy("updated desc").Find(&ms)
	if err != nil {
		return ms, errcode.NewError(errcode.DaoFailed,err)
	}
	return ms, nil
}
